package com.qyhl.module_home.city.bestone;

import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.module_home.R;
import com.qyhl.module_home.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.home.BestoneItemTypeBean;
import com.qyhl.webtv.commonlib.entity.home.BestoneTypeBean;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

@Route(path = ARouterPathConstant.BESTONE_TYPE)
public class BestoneActivity extends BaseActivity implements BestoneContract.BestoneView {
    @BindView(R2.id.loadMask)
    LoadingLayout loadMask;
    @BindView(R2.id.classList)
    RecyclerView classList;
    @BindView(R2.id.searchList)
    RecyclerView searchList;
    @BindView(R2.id.searchClear)
    ImageView searchClear;
    @BindView(R2.id.gosearch)
    ImageView gosearch;
    @BindView(R2.id.back)
    ImageView back;
    @BindView(R2.id.searchText)
    EditText searchText;

    private BestoneContract.BestonePresenter presenter;

    private ClassAdapter adapter;
    private SearchAdapter searchAdapter;
    private ArrayList<BestoneTypeBean> datas;
    private ArrayList<BestoneItemTypeBean> serachDatas;
    /**
     * 控制能否搜索
     */
    private boolean isCanSearch = true;
    /**
     * 记录类型列表加载状态
     */
    private int classType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.home_activity_bestone;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        inits();
    }

    @Override
    protected void setListener() {

    }

    private void inits() {
        loadMask.setStatus(LoadingLayout.Loading);
        presenter = new BestonePresenter(this);

        initClassList();

        back.setOnClickListener(v -> finish());
        //类型列表获取失败点击重试
        loadMask.setOnReloadListener(view -> {
            loadMask.setStatus(LoadingLayout.Loading);
            presenter.getData();
        });

        //搜索输入监听
        searchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(searchText.getText().toString())) {
                    searchClear.setVisibility(View.GONE);
                    showTypeList(true);
                    loadMask.setStatus(classType);
                } else {
                    searchClear.setVisibility(View.VISIBLE);
                }
            }
        });

        //搜索清空输入
        searchClear.setOnClickListener(v -> searchText.setText(""));

        //搜索
        gosearch.setOnClickListener(v -> {
            if (isCanSearch) {
                String text = searchText.getText().toString();
                if (!TextUtils.isEmpty(text) && !TextUtils.isEmpty(text.trim())) {
                    text = text.trim();
                    if (serachDatas == null) {
                        initSearchList();
                    }
                    searchAdapter.setInputText(text);
                    showTypeList(false);
                    loadMask.setStatus(LoadingLayout.Loading);
                    presenter.search(text);
                    //搜索过程中不允许再次搜索
                    isCanSearch = false;
                }
            }
            InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(searchText.getWindowToken(), 0);
        });
        presenter.getData();
    }

    /**
     * 类型列表初始化
     */
    private void initClassList() {
        datas = new ArrayList<>();
        //网格纵向布局
        classList.setLayoutManager(new GridLayoutManager(this, 2,
                OrientationHelper.VERTICAL, false));
        adapter = new ClassAdapter(this, datas);
        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                Bundle bundle = new Bundle();
                bundle.putString("typeid", String.valueOf(datas.get(i).getId()));
                bundle.putString("title", datas.get(i).getTypeName());
                RouterManager.router(ARouterPathConstant.BESTONE_TYPE_LIST,bundle);

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });
        classList.setAdapter(adapter);
    }

    /**
     * 是否显示类型列表布局
     */
    private void showTypeList(boolean isType) {
        if (isType) {
            classList.setVisibility(View.VISIBLE);
            searchList.setVisibility(View.GONE);
        } else {
            classList.setVisibility(View.GONE);
            searchList.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 获取类型列表失败
     */
    @Override
    public void getDataError(String msg) {
        loadMask.setStatus(LoadingLayout.Error);
        classType = LoadingLayout.Error;
    }

    /**
     * 获取类型列表成功
     */
    @Override
    public void getDataSuccess(List<BestoneTypeBean> data) {
        datas.clear();
        datas.addAll(data);
        adapter.notifyDataSetChanged();
        loadMask.setStatus(LoadingLayout.Success);
        classType = LoadingLayout.Success;
    }

    /**
     * 搜索失败
     */
    @Override
    public void searchError(String msg) {
        Toasty.normal(this, msg).show();
        loadMask.setErrorText(msg);
        loadMask.setStatus(LoadingLayout.Error);
        isCanSearch = true;
    }

    /**
     * 搜索列表初始化
     */
    private void initSearchList() {
        serachDatas = new ArrayList<>();
        //纵向线性布局
        searchList.setLayoutManager(new LinearLayoutManager(this));
        searchAdapter = new SearchAdapter(this, serachDatas);
        searchList.setAdapter(searchAdapter);
    }

    /**
     * 搜索成功
     */
    @Override
    public void searchSuccess(List<BestoneItemTypeBean> data) {
        isCanSearch = true;
        if (data == null || data.isEmpty()) {
            loadMask.setEmptyImage(0);
            loadMask.setEmptyText("无搜索结果");
            loadMask.setStatus(LoadingLayout.Empty);
        } else {
            loadMask.setStatus(LoadingLayout.Success);
            serachDatas.clear();
            serachDatas.addAll(data);
            searchAdapter.notifyDataSetChanged();
        }
    }
}
